package servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import pojo.Cart;
import pojo.Customer;
import pojo.Order;
import pojo.UserAddress;

import service.CartServicea;
import service.OrderService;
import service.ProductService;
import service.UserAddressService;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method=request.getParameter("method");
		switch(method) {
		case "confirm":
			confirm(request,response);
			break;
		case "addorder":
			addorder(request,response);
			break;
		}
//		if(method.equals("del")) {
//			del(request,response);
//		}else if(method.equals("add")) {
//			add(request,response);
//		}
	}

	private void addorder(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		HttpSession session=((HttpServletRequest)request).getSession();
		Customer cu=(Customer)session.getAttribute("c");
		String addressid=request.getParameter("addressid");
		String orderid=UUID.randomUUID()+"";
		String orderstate="未支付";
		String orderType="支付宝";
		String userId=cu.getC_name();
		Date d=new Date();
		System.out.println(addressid+" "+orderid+" "+orderstate+" "+orderType+" "+userId);
		String createTime=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(d);
		String[]cids=request.getParameterValues("cid");
		String[]quantity=request.getParameterValues("pquantity");
		String[]price=request.getParameterValues("pprice");
		String[]amount=request.getParameterValues("pamount");
		String[]pids=request.getParameterValues("pid");
		int count=0;float sum=0;
		for(String s:quantity) {
			count+=Integer.parseInt(s);
		}
		for(String s:amount) {
			sum+=Float.parseFloat(s);
		}
		Order order=new Order(orderid,orderstate,createTime,orderType,Integer.parseInt(addressid),userId,count,sum);
		OrderService oService=new OrderService();
		int flag=oService.addorder(order);
		System.out.println(flag+"sckjdvcn");
		if(flag>0) {
			CartServicea cartservice=new CartServicea();
			ProductService pservice=new ProductService();
			for(int i=0;i<cids.length;i++) {
				System.out.println("orderservlet...."+pids[i]+" "+quantity[i]);
				cartservice.updateCartOrderId(Integer.parseInt(cids[i]), orderid);
				pservice.updateQuantity(pids[i], Integer.parseInt(quantity[i]));

			}
			request.setAttribute("order",order);
					try {
						response.sendRedirect("index.jsp");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				//还要修改Cart表，给cid对应的行添加orderid
				}

	private void confirm(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		HttpSession session=((HttpServletRequest)request).getSession();
		Customer cu=(Customer)session.getAttribute("c");
		String ids[] = request.getParameterValues("pid");
		Cart t = null;
		List<Cart> list = new ArrayList<Cart>();
		CartServicea cService = new CartServicea();
		for(String id:ids) {
			t = cService.getOne(id);
			list.add(t);
		}
		UserAddressService addressService = new UserAddressService();
		List<UserAddress> listaddress = addressService.getAddressByUserId(cu.getC_name());
		request.setAttribute("cartlist", list);
		request.setAttribute("addresslist", listaddress);
		try {
			request.getRequestDispatcher("confirm.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

//	private void add(HttpServletRequest request, HttpServletResponse response) {
//		// TODO Auto-generated method stub
//		try {
//			request.setCharacterEncoding("utf-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		HttpSession session=request.getSession(true);
//		Customer cu=(Customer)session.getAttribute("a");
//		String pid=request.getParameter("p_id");
//		String image=request.getParameter("p_image");
//		Float price=Float.parseFloat(request.getParameter("p_price"));
//		String name=request.getParameter("p_name");
//		int quantity=Integer.parseInt(request.getParameter("quantity"));
//		int amount=Integer.parseInt(request.getParameter("amount"));
//		OrderService service=new OrderService();
//		Order order=new Order();
//			order.setC_name(cu.getC_name());
//			order.setP_id(pid);
//			order.setP_image(image);
//			order.setP_name(name);
//			order.setP_price(price);
//			order.setQuantity(quantity);
//			order.setAmount(amount);
//			int flag=service.addOrder(order);
//			if(flag>0){
//				try {
//					response.sendRedirect("showOrder.jsp");
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//	}
//
//	private void del(HttpServletRequest request, HttpServletResponse response) {
//		// TODO Auto-generated method stub
//		int pid=Integer.parseInt(request.getParameter("pid"));
//		OrderService oservice = new OrderService();
//		int flag = oservice.delorder(pid);
//		if(flag>0){
//		try {
//			response.sendRedirect("showCart.jsp");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		}else {
//			try {
//				response.sendRedirect("fail.jsp");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//	}

}
